"""
API路由模块
处理邮件收发、管理等API接口
"""
from datetime import datetime
from flask import request, jsonify
from flask_login import login_required, current_user
from app.api import bp
from app.models import User, Email
from app import db
from sqlalchemy import or_, and_

@bp.route('/emails/send', methods=['POST'])
@login_required
def send_email():
    """
    发送邮件API
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        data = request.get_json()
        
        recipient_username = data.get('recipient', '').strip()
        subject = data.get('subject', '').strip()
        content = data.get('content', '').strip()
        
        # 验证输入
        if not recipient_username:
            return jsonify({'success': False, 'message': '请输入收件人'}), 400
        
        if not subject:
            return jsonify({'success': False, 'message': '请输入邮件主题'}), 400
        
        if not content:
            return jsonify({'success': False, 'message': '请输入邮件内容'}), 400
        
        # 检查收件人是否存在
        recipient = User.query.filter_by(username=recipient_username).first()
        if not recipient:
            return jsonify({'success': False, 'message': '收件人不存在'}), 404
        
        # 检查收件人是否为活跃用户
        if not recipient.is_active:
            return jsonify({'success': False, 'message': '收件人账号已被禁用'}), 400
        
        # 不能给自己发邮件
        if recipient.id == current_user.id:
            return jsonify({'success': False, 'message': '不能给自己发送邮件'}), 400
        
        # 创建邮件
        email = Email(
            sender_id=current_user.id,
            recipient_id=recipient.id,
            subject=subject,
            content=content
        )
        
        db.session.add(email)
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'邮件已成功发送给 {recipient_username}',
            'email_id': email.id
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'发送失败：{str(e)}'}), 500

@bp.route('/emails/inbox')
@login_required
def get_inbox():
    """
    获取收件箱邮件列表API
    
    Returns:
        JSON响应包含邮件列表
    """
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()
        
        # 构建查询
        query = Email.query.filter(
            Email.recipient_id == current_user.id,
            Email.is_deleted_by_recipient == False
        )
        
        # 搜索功能
        if search:
            query = query.filter(
                or_(
                    Email.subject.contains(search),
                    Email.content.contains(search)
                )
            )
        
        # 分页
        emails = query.order_by(Email.sent_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 序列化邮件数据
        email_list = []
        for email in emails.items:
            email_data = email.to_dict()
            email_data['sender_username'] = email.sender.username
            email_list.append(email_data)
        
        return jsonify({
            'success': True,
            'emails': email_list,
            'pagination': {
                'page': emails.page,
                'pages': emails.pages,
                'per_page': emails.per_page,
                'total': emails.total,
                'has_next': emails.has_next,
                'has_prev': emails.has_prev
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取邮件失败：{str(e)}'}), 500

@bp.route('/emails/sent')
@login_required
def get_sent():
    """
    获取已发送邮件列表API
    
    Returns:
        JSON响应包含邮件列表
    """
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()
        
        # 构建查询
        query = Email.query.filter(
            Email.sender_id == current_user.id,
            Email.is_deleted_by_sender == False
        )
        
        # 搜索功能
        if search:
            query = query.filter(
                or_(
                    Email.subject.contains(search),
                    Email.content.contains(search)
                )
            )
        
        # 分页
        emails = query.order_by(Email.sent_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 序列化邮件数据
        email_list = []
        for email in emails.items:
            email_data = email.to_dict()
            email_data['recipient_username'] = email.recipient.username
            email_list.append(email_data)
        
        return jsonify({
            'success': True,
            'emails': email_list,
            'pagination': {
                'page': emails.page,
                'pages': emails.pages,
                'per_page': emails.per_page,
                'total': emails.total,
                'has_next': emails.has_next,
                'has_prev': emails.has_prev
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取邮件失败：{str(e)}'}), 500

@bp.route('/emails/<int:email_id>')
@login_required
def get_email(email_id):
    """
    获取邮件详情API
    
    Args:
        email_id: 邮件ID
    
    Returns:
        JSON响应包含邮件详情
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        # 权限检查：只有发件人或收件人可以查看
        if email.sender_id != current_user.id and email.recipient_id != current_user.id:
            return jsonify({'success': False, 'message': '无权查看此邮件'}), 403
        
        # 检查邮件是否被删除
        if ((email.sender_id == current_user.id and email.is_deleted_by_sender) or
            (email.recipient_id == current_user.id and email.is_deleted_by_recipient)):
            return jsonify({'success': False, 'message': '邮件不存在'}), 404
        
        # 如果是收件人查看，标记为已读
        if email.recipient_id == current_user.id and not email.is_read:
            email.mark_as_read()
            db.session.commit()
        
        # 序列化邮件数据
        email_data = email.to_dict()
        email_data['sender_username'] = email.sender.username
        email_data['recipient_username'] = email.recipient.username
        
        return jsonify({
            'success': True,
            'email': email_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取邮件失败：{str(e)}'}), 500

@bp.route('/emails/<int:email_id>/read', methods=['POST'])
@login_required
def mark_email_read(email_id):
    """
    标记邮件为已读API
    
    Args:
        email_id: 邮件ID
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        # 只有收件人可以标记为已读
        if email.recipient_id != current_user.id:
            return jsonify({'success': False, 'message': '无权操作此邮件'}), 403
        
        # 检查邮件是否被删除
        if email.is_deleted_by_recipient:
            return jsonify({'success': False, 'message': '邮件不存在'}), 404
        
        email.mark_as_read()
        db.session.commit()
        
        return jsonify({'success': True, 'message': '邮件已标记为已读'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'}), 500

@bp.route('/emails/<int:email_id>/delete', methods=['POST'])
@login_required
def delete_email(email_id):
    """
    删除邮件API
    
    Args:
        email_id: 邮件ID
    
    Returns:
        JSON响应包含操作结果
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        # 权限检查：只有发件人或收件人可以删除
        if email.sender_id != current_user.id and email.recipient_id != current_user.id:
            return jsonify({'success': False, 'message': '无权删除此邮件'}), 403
        
        # 标记删除
        if email.sender_id == current_user.id:
            if email.is_deleted_by_sender:
                return jsonify({'success': False, 'message': '邮件已被删除'}), 400
            email.is_deleted_by_sender = True
        
        if email.recipient_id == current_user.id:
            if email.is_deleted_by_recipient:
                return jsonify({'success': False, 'message': '邮件已被删除'}), 400
            email.is_deleted_by_recipient = True
        
        # 如果双方都删除了，物理删除邮件
        if email.is_deleted_by_sender and email.is_deleted_by_recipient:
            db.session.delete(email)
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': '邮件已删除'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除失败：{str(e)}'}), 500

@bp.route('/users/search')
@login_required
def search_users():
    """
    搜索用户API
    
    Returns:
        JSON响应包含用户列表
    """
    try:
        query = request.args.get('q', '').strip()
        limit = request.args.get('limit', 10, type=int)
        
        if not query:
            return jsonify({'success': True, 'users': []})
        
        # 搜索用户（排除自己）
        users = User.query.filter(
            and_(
                User.id != current_user.id,
                User.is_active == True,
                or_(
                    User.username.contains(query),
                    User.email.contains(query)
                )
            )
        ).limit(limit).all()
        
        # 序列化用户数据
        user_list = []
        for user in users:
            user_list.append({
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role': user.role
            })
        
        return jsonify({
            'success': True,
            'users': user_list
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'搜索失败：{str(e)}'}), 500

@bp.route('/stats')
@login_required
def get_stats():
    """
    获取用户邮件统计信息API
    
    Returns:
        JSON响应包含统计信息
    """
    try:
        # 收件箱统计
        inbox_total = Email.query.filter(
            Email.recipient_id == current_user.id,
            Email.is_deleted_by_recipient == False
        ).count()
        
        inbox_unread = Email.query.filter(
            Email.recipient_id == current_user.id,
            Email.is_deleted_by_recipient == False,
            Email.is_read == False
        ).count()
        
        # 已发送统计
        sent_total = Email.query.filter(
            Email.sender_id == current_user.id,
            Email.is_deleted_by_sender == False
        ).count()
        
        return jsonify({
            'success': True,
            'stats': {
                'inbox_total': inbox_total,
                'inbox_unread': inbox_unread,
                'sent_total': sent_total
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计失败：{str(e)}'}), 500